#!/bin/bash
#build rootfs
if [ "$(id -u)" != "0" ]; then
   echo "Script must be run as root !"
   exit 0
fi
image_name=${BOARD}-${OPI_SYSTEM_TYPE}-${OPI_SYSTEM_VERSION}".img"
image_file=${OPI_OUTPUT_DIR}/$image_name
image_size=${OPI_IMAGE_SIZE}
boot_size=${OPI_IMAGE_BOOT_SIZE}
boot_start=${OPI_IMAGE_BOOT_START}

read -p "Input image size :" value
$image_size?=$value
read -p "Input boot partition size :" value
$boot_size?=$value

boot_end=$(expr 2048 \* $boot_size )
root_size=$(expr $image_size - $boot_size)
root_start=$(expr $boot_end + 1)
root_end=$(expr 2048 \* $root_size )

echo ""
echo " image name :	$image_name"
echo " image size :	$image_size	M"
echo ""
echo " boot start : $boot_start"
echo " boot end   : $boot_end"
echo " boot partition size :  $boot_size	M"
echo ""
echo " root start : $root_start"
echo " root end   : $root_end"
echo " root partition size :  $root_size	M"
echo ""


message "check installed software ....."
apt-get install -y -q parted kpartx losetup

# Create the disk and partition it
# We start out at around 2MB so there is room to write u-boot without issues.
echo "Creating image file for OrangePi"
dd if=/dev/zero of=$image_file bs=1M count=$image_size
parted $image_file --script -- mklabel msdos
parted $image_file --script -- mkpart primary fat32 $(boot_start)s $(boot_end)s
parted $image_file --script -- mkpart primary ext4 $(root_start)s 100%

# Set the partition variables
loopdevice=`losetup -f --show $image_file`
device=`kpartx -va $loopdevice| sed -E 's/.*(loop[0-9])p.*/\1/g' | head -1`
sleep 5
device="/dev/mapper/${device}"
bootp=${device}p1
rootp=${device}p2

# Create file systems
mkfs.vfat $bootp
mkfs.ext4 $rootp

# Create the dirs for the partitions and mount them
mkdir -p $OPI_IMAGE_DIR
mkdir -p ${OPI_IMAGE_DIR}/bootp
mkdir -p ${OPI_IMAGE_DIR}/rootp
mount $bootp ${OPI_IMAGE_DIR}/bootp
mount $rootp ${OPI_IMAGE_DIR}/rootp

echo "Rsyncing rootfs into image file"
rsync -HPavz -q ${OPI_OUTPUT_DIR}/rootfs/ ${OPI_IMAGE_DIR}/rootp


# Unmount partitions
umount $bootp
umount $rootp
kpartx -dv $loopdevice

#dd if=${basedir}/../misc/nanopi2/bootloader of=$loopdevice bs=512 seek=65
sync


losetup -d $loopdevice

echo ""
echo "^_^"
